import request from '@/utils/request'
import { onMounted, onUnmounted } from 'vue'
import { JSONParse } from 'wft-utils'

interface TItem {
  key: string,
  value: string
}

let timer: number | null = null

export function useRequest(curComp: TComp, init?: () => void) {
  const { server } = curComp
  onMounted(() => {
    if(server.dataType == '0') {
      if(init) init()
    } else {
      requestHandler(curComp)
      if(server.isLoop) {
        timer = setInterval(() => {
          requestHandler(curComp)
        }, server.loopTime * 1000)
      }
    }
  })
  onUnmounted(() => {
    if(timer) {
      clearInterval(timer)
      timer = null
    }
  })
}

function requestHandler(curComp: TComp) {
  const { server } = curComp
  let url = server.config.url
  let method = server.config.method
  let headers = getOptions(server.config.headers)
  let params = getOptions(server.config.params)
  let data = getOptions(server.config.body)
  request({ url, method, headers, params, data }).then(res => {
    const func = new Function('res', server.handler)
    curComp.data = func(res)
  })
}

function getOptions(data: Array<TItem> = []) {
  const target: { [PropName: string]: any } = {}
  data.forEach((item: TItem) => {
    try {
      target[item.key] = JSONParse(item.value)
      if(typeof target[item.key] !== 'object') {
        target[item.key] = String(target[item.key])
      }
    }catch(e) {
      target[item.key] = item.value
    }
  })
  return target
}